package org.jeecg.modules.wms.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码工具类
 */
public class QRCodeUtil {

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static final String FORMAT = "png";
    private static final int WIDTH = 300;
    private static final int HEIGHT = 300;
    // 带文本信息的二维码高度需要更高
    private static final int HEIGHT_WITH_INFO = 380;
    // 字体设置
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 16);
    private static final Font INFO_FONT = new Font("微软雅黑", Font.PLAIN, 14);

    /**
     * 生成二维码
     *
     * @param content 二维码内容
     * @param filePath 保存路径
     * @throws WriterException 编码异常
     * @throws IOException IO异常
     */
    public static void encode(String content, String filePath) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        
        ImageIO.write(image, FORMAT, file);
    }
    
    /**
     * 生成带信息的二维码，包含仓库编号、库位编号、库位名称等信息
     *
     * @param content 二维码内容
     * @param filePath 保存路径
     * @param warehouseCode 仓库编号
     * @param locationCode 库位编号
     * @param locationName 库位名称
     * @throws WriterException 编码异常
     * @throws IOException IO异常
     */
    public static void encodeWithInfo(String content, String filePath, String warehouseCode, String locationCode, String locationName) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage qrImage = toBufferedImage(bitMatrix);
        
        // 创建带信息的图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT_WITH_INFO, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        
        // 设置背景为白色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT_WITH_INFO);
        
        // 绘制二维码
        g2d.drawImage(qrImage, 0, 0, null);
        
        // 绘制库位信息
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // 绘制库位名称（标题）
        g2d.setFont(TITLE_FONT);
        g2d.setColor(Color.BLACK);
        FontMetrics titleFontMetrics = g2d.getFontMetrics();
        String titleText = locationName != null ? locationName : "";
        int titleWidth = titleFontMetrics.stringWidth(titleText);
        g2d.drawString(titleText, (WIDTH - titleWidth) / 2, HEIGHT + 25);
        
        // 绘制仓库编号和库位编号信息
        g2d.setFont(INFO_FONT);
        g2d.setColor(new Color(51, 51, 51)); // 深灰色
        FontMetrics infoFontMetrics = g2d.getFontMetrics();
        
        String warehouseText = "仓库：" + (warehouseCode != null ? warehouseCode : "");
        int warehouseWidth = infoFontMetrics.stringWidth(warehouseText);
        g2d.drawString(warehouseText, (WIDTH - warehouseWidth) / 2, HEIGHT + 50);
        
        String locationText = "库位：" + (locationCode != null ? locationCode : "");
        int locationWidth = infoFontMetrics.stringWidth(locationText);
        g2d.drawString(locationText, (WIDTH - locationWidth) / 2, HEIGHT + 70);
        
        g2d.dispose();
        
        // 保存图片
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        
        ImageIO.write(image, FORMAT, file);
    }

    /**
     * 将位矩阵转换为图像
     *
     * @param matrix 位矩阵
     * @return 图像
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        
        return image;
    }
} 